#python中通过类实现多线程的练习

import threading
import random
import time

glock=threading.Lock()
gmoney=1000
gtimes=10

class productor(threading.Thread):
    def run(self):
        while True:
            money=random.randint(100,1000)
            global gmoney
            global gtimes
            glock.acquire()
            if gtimes>0:
                gtimes-=1
                gmoney+=money
                print('%s生产了%s元'%(threading.current_thread(),money))
            else:
                print('%s结束了!'%threading.current_thread())
                glock.release()
                break
            glock.release()
            time.sleep(1)

class consume(threading.Thread):
    def run(self):
        while True:
            money=100
            global gmoney
            glock.acquire()
            if gmoney>=100:
                gmoney-=money
                print('%s消费了%s元'%(threading.current_thread(),money))
            else:
                print('%s正在等待，余额不足!'%(threading.current_thread()))
                glock.release()
                break
            glock.release()
            time.sleep(1)

for i in range(3):
    t=productor()
    t.start()

for i in range(3):
    t=consume()
    t.start()
